package cz.proks.easyhelpdesk.gae.api.impl.db;

import java.util.LinkedList;
import java.util.List;

import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cz.proks.easyhelpdesk.api.HelpdeskApi;
import cz.proks.easyhelpdesk.api.config.Configuration;
import cz.proks.easyhelpdesk.api.exception.ApiException;
import cz.proks.easyhelpdesk.api.model.Helpdesk;
import cz.proks.easyhelpdesk.gae.api.impl.dbo.HelpdeskMember;

@Repository(Configuration.DB.HELPDESK_API)
@Scope("prototype")
public class HelpdeskApiImpl extends BaseApiImpl<Helpdesk> implements HelpdeskApi {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @Override
    protected Class<Helpdesk> getDomainClass() {
        return Helpdesk.class;
    }
    
    @Override
    protected Helpdesk getDboObject(Helpdesk entity) {
        cz.proks.easyhelpdesk.gae.api.impl.dbo.Helpdesk dbo = instantiateDbo(entity);

        if (dbo != null)
            dbo.toDbo(entity);

        return dbo;
    }    

    @Override
    @Transactional(readOnly = true)
    public List<Helpdesk> listForUser(Long userId) throws ApiException {
        log.debug("listForUser():: Start with userId '{}'", userId);
        
        Query queryHM = getEntityManager().createNamedQuery("HelpdeskMember.listForUser");
        queryHM.setParameter("userId", userId);
        List<HelpdeskMember> dboHeldpeskMembers = queryHM.getResultList();
        
        List<Long> helpdeskIds = new LinkedList<Long>();
        if (dboHeldpeskMembers != null)
            for (HelpdeskMember dboHelpdeskMember : dboHeldpeskMembers)
                helpdeskIds.add(dboHelpdeskMember.getHelpdeskId());
        
        Query query = getEntityManager().createNamedQuery("Helpdesk.listForUser");
        query.setParameter("helpdeskIds", helpdeskIds);
        List<Helpdesk> entityList = new LinkedList<Helpdesk>();
        
        if (!helpdeskIds.isEmpty())
            try {            
                List<cz.proks.easyhelpdesk.gae.api.impl.dbo.Helpdesk> dboList = query.getResultList();
                entityList.addAll(fromDboList(dboList));
            } catch (EmptyResultDataAccessException erdae) {
                // NOP
            }
                 
        log.debug("listForUser():: Exit with {} entities", entityList != null ? entityList.size() : null);
        return entityList;
    }    
}
